package com.jiang.validate;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

public class ValidateUtils {

	private ValidateUtils() {

	}

	// 验证方法
	public static Map<String, Object> validate(HandlerMethod handlerMethod, HttpServletRequest request) {

		Map<String, Object> errors = new HashMap<>(); // 保存错误的集合
		// 通过拦截器去寻找是否是要验证的方法key
		String key = handlerMethod.getBean().getClass().getSimpleName() + "." + handlerMethod.getMethod().getName()
				+ ".rule";

		try {
			// 通过反射寻找值
			Method getValueMethod = handlerMethod.getBean().getClass().getMethod("getResourceValue", String.class,
					Object[].class);
			String value = (String) getValueMethod.invoke(handlerMethod.getBean(), key, null);
			if (StringUtils.isNotBlank(value)) {
				 // EmpAction.addEmp.rule=empNo:string|salary:double|birthday:date
				// 获得所有的参数，然后逐个验证
				MethodParameter[] methodParameters = handlerMethod.getMethodParameters();
				for (int i = 0; methodParameters.length > 0 && i < methodParameters.length; i++) {
					addErrors(value, handlerMethod,request, errors);
				}
			}
		} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException
				| SecurityException e) {
			e.printStackTrace();
		}
		// 增加上传图片验证
		if(errors.size()==0) {
			MultipartResolver mr = new CommonsMultipartResolver(); // 关键的是判断是否有文件上传类
			if(mr.isMultipart(request)) { // 表示当前有上传文件
				String mimeKey = handlerMethod.getBean().getClass().getSimpleName() + "." + handlerMethod.getMethod().getName()
						+ ".mime.rule";
				Method getValueMethod;
				try {
					getValueMethod = handlerMethod.getBean().getClass().getMethod("getResourceValue", String.class,
							Object[].class);
					String value = (String) getValueMethod.invoke(handlerMethod.getBean(), mimeKey, null);
					// image/jpeg|image/jpg|image/png|image/gif|image/bmp
					if(StringUtils.isNotBlank(value)) {
						String[] eachColumnTypes = value.split("\\|");
						MultipartRequest req = (MultipartRequest) request;
						Map<String, MultipartFile> fileMap = req.getFileMap();
						if(fileMap!=null && !fileMap.isEmpty()) {
							for(Map.Entry<String, MultipartFile> entry: fileMap.entrySet()) {
								// 每一个文件进行校验
								if(!ValidateRuleUtils.isMime(eachColumnTypes, entry.getValue().getContentType())) {
									errors.put(entry.getKey(), getValueMethod.invoke(handlerMethod.getBean(), "validation.mime.msg", null));
								}
							}
						}
						
					}
				} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
					e.printStackTrace();
				}
			
			}
		}
		return errors;
	}

	// 逐个验证，如果有错加入集合Map中
	private static void addErrors(String ruleValue, HandlerMethod handlerMethod, HttpServletRequest request, Map<String, Object> errors) throws NoSuchMethodException, SecurityException,
			IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//		String param_name = methodParameter.getParameterName(); // 注意使用这个方法是拿不到参数名称的
		// 通过反射寻找值
		Method getValueMethod = handlerMethod.getBean().getClass().getMethod("getResourceValue", String.class, Object[].class);
		// EmpAction.addEmp.rule=empNo:string|salary:double|birthday:date
		String[] eachColumnTypes = ruleValue.split("\\|");
		for (String eachColumnType : eachColumnTypes) {
			String eachColumn = eachColumnType.split("\\:")[0];
			String eachType = eachColumnType.split("\\:")[1];
			String value = request.getParameter(eachColumn);
			switch (eachType) {
				case "int": {
					if (!ValidateRuleUtils.isNumber(value)) {
						String valuemsg = (String) getValueMethod.invoke(handlerMethod.getBean(), "validation.int.msg",
								null);
						errors.put(eachColumn, valuemsg);
					}
					break;
				}
				case "double": {
					if (!ValidateRuleUtils.isDouble(value)) {
						String valuemsg = (String) getValueMethod.invoke(handlerMethod.getBean(), "validation.double.msg",
								null);
						errors.put(eachColumn, valuemsg);
					}
					break;
				}
				case "date": {
					if (!ValidateRuleUtils.isDate(value)) {
						String valuemsg = (String) getValueMethod.invoke(handlerMethod.getBean(), "validation.date.msg",
								null);
						errors.put(eachColumn, valuemsg);
					}
					break;
				}
				case "string": {
					if (!ValidateRuleUtils.isString(value)) {
						String valuemsg = (String) getValueMethod.invoke(handlerMethod.getBean(), "validation.string.msg",
								null);
						errors.put(eachColumn, valuemsg);
					}
					break;
				}
				default:
					break;
				}

		}

	}

}
